package RnD;

import Rout.*;
import com.sun.org.omg.SendingContext.CodeBasePackage.URLSeqHelper;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Keys;
import org.testng.annotations.*;

public class SimpleCatcher {

    private GoBefore browser = new GoBefore();
    private ArrayList<String> urls = new ArrayList<String>();
    private int attempt = 3;   // how much we'll try for catch events
    private static String TESTRUN = "\n Run test: ", TESTCASE = "\n\nTest case: ", TESTNAME = "test_", NOTFOUND = "Ads not found";
    private String NextUrl;
    private CsvFileWriter toCsv;
    private String AdNetwork;
    private String Referal;
    private Map<String, String> map;
    private String GEO, BrowserName, OSName;


    @BeforeMethod
    public void setUp() throws Exception {

        map = new HashMap<String, String>();

        map.put("Propellerads", "http://onclickads.net/afu.php?zoneid=265284");
        map.put("Adcash", "http://www.youradexchange.com/ad/display.php?r=266267");
        map.put("YTZ", "http://pmn.perfecttrkloop.com/?s1={S1}&s2={S2}&s3={S3}&s4={S4}&s5={S5}");
        map.put("Adsupply-FileStorage", "http://engine.trklnks.com/link.engine?guid=fdb724e4-cdea-4b68-ba31-676a1c4ce5ab&Hardlink=true&time=0");
        map.put("Adsupply-Downloads", "http://engine.trklnks.com/link.engine?guid=c00f2813-bc69-4ae3-8cbd-2d492fd02bd3&Hardlink=true&time=0");
        map.put("Adsupply-Streaming", "http://engine.trklnks.com/link.engine?guid=9f4d83e3-381c-4c1c-9b10-bb43849270da&Hardlink=true&time=0");
       
        urls.addAll(map.values());
        System.out.println(urls);               

        System.out.println(TESTRUN + getClass().getSimpleName());
        browser.setXpFilename(null);
        browser.setEnableSafeBrow(Boolean.FALSE);
//        browser.setChDrvPath("/home/user/Dropbox/WebDriver/lin64/chromedriver");
//        browser.setRemoteDriver("192.168.5.193"); //Win7Clone VBox
        browser.setRemoteDriver("192.168.4.219"); //Win7x32 VBox
//	
        browser.setTimeToWait(1);
        browser.setNoJavaScript(true);
        System.out.println("Time to wait: "+browser.getTimeToWait());
    }

    public void closeAlerts() throws Exception {
        Thread.sleep(1000);
        try {            
                browser.getClicker().sendKeys(Keys.ENTER).build().perform();                
        }
            catch(Exception ex){
                try {
                    ((JavascriptExecutor) browser.getDriver()).executeScript("window.confirm = function(msg) { return true; }");
                ((JavascriptExecutor) browser.getDriver()).executeScript("window.alert = function(msg) { return true; }");                             
        } catch (Exception e) { 
            System.out.println("try to close");
                    try {
                        browser.getDriver().switchTo().alert().accept();
                        
                    } catch (Exception ess) {
                        try {
                            browser.getDriver().switchTo().alert().accept();
                            browser.getDriver().switchTo().alert().accept();
                        } catch (Exception esad) {
                        }
                    }            
            browser.closaAlert();   
        }
            }      
    }
    
    
    public String detectGEO() throws Exception {
        
        browser.setUp();
        GEO = browser.detectGEO();
        browser.getDriver().quit();
        return GEO;
    }

    @Test //Void Footer Baner
    public void Test() throws Exception {
                
        for (int i = 0; i <= 6; i++) {
            toCsv = new CsvFileWriter(9);
            browser.setUserAg(i);
            if (i == 3 || i == 6) {
                browser.resizeBrowser(460, 840);
            }
            
            browser.setUp();
            GEO = browser.detectGEO();
            for (Map.Entry<String, String> url: map.entrySet()) {

                AdNetwork = url.getKey();
                BrowserName = browser.getUsAgBrName();
                OSName = browser.getUsAgOsName();
                int curTest = (url.getKey().indexOf(url.getKey()) + 1);
                
                browser.setCurURL(url.getValue());
                System.out.println(TESTCASE + curTest);
                
//                Thread.sleep(1000000);
                                
                browser.setRepDir(TESTNAME + AdNetwork+"_"+"_"+BrowserName+"_"+OSName + "_" + GEO);
                browser.setCustomSrcDir("screenshots/"+browser.getRepDir());
                

                System.out.println("\nTest URL is: " + url.getValue());
                System.out.println("Adv: " + AdNetwork);
                int retryCount = 1;
                for (int j = 0; j < retryCount; j++) {                                   
                    try {
                         TestIN(url);
                    } catch (Exception e) {
                        System.out.println("second chance: " + j);
                        retryCount++;                        
                    }                
               }
                browser.closaAlert();
                
                toCsv.writeCsvFile("test_" + GEO+BrowserName+OSName + ".csv");
            
                }
                
            closeAlerts();
            browser.getDriver().quit();
            
        }
//    }
//        browser.getDriver().close();
    }
    @Test
    public void TestIN(Map.Entry<String, String> url) throws Exception{
        for (int m=0; m < attempt; m++) {                    
                    
        System.out.println("attempt :" + m);
//                    browser.getDriver().get(url.getValue());
                    try {
                        closeAlerts();  
                        browser.getDriver().get(url.getValue());
                        closeAlerts();
                    } catch (Exception ext) {
                        System.out.println("catch");
                        closeAlerts();                        
                    }
                    try {
                        NextUrl = browser.getDriver().getCurrentUrl();                        
                    } catch (Exception e) {
                        System.out.println("catch");
                        closeAlerts();
                        try {
                            closeAlerts();
                            NextUrl = browser.getDriver().getCurrentUrl();

                        } catch (Exception ex) {
                            closeAlerts();
                            browser.closaAlert();
                            NextUrl = browser.getDriver().getCurrentUrl();
                        }
                        
                    }
                   
                   try {
                browser.takeFoto();
            } catch (Exception e) {                
                closeAlerts();
                browser.closaAlert();
                browser.takeFoto();
            }
 
                                       

                    System.out.println("Redirect to: " + NextUrl);
                    try {
                        closeAlerts();
                Referal = (browser.getReferal(browser.getDriver(), NextUrl));
            } catch (Exception e) {
                closeAlerts();
                browser.closaAlert();
                Referal = (browser.getReferal(browser.getDriver(), NextUrl));
                
            }
                    
                    System.out.println("Redirect via URL: " + Referal);
                    System.out.println("!" + browser.getFotoName() + "|thumbnail!");
                    System.out.println(toCsv.createArrayList(AdNetwork, GEO, OSName, BrowserName, NextUrl, browser.getFotoName(), Referal));
        }
    }
    
    
    @AfterMethod
    public void Down() throws Exception {
        toCsv.writeCsvFile("test_" + GEO + ".csv");
        browser.getDriver().quit();

    }

}
